#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json

from bottle import Bottle
from bottle import request, response

from conn.MyPagerFactory import MyPager

WebProCampAdm = Bottle()


@WebProCampAdm.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@WebProCampAdm.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


class WebProjectCampRoute:
    ERROR_CODE = {
        "80": "数据读取异常错误，请联系管理员",
        "99": "处理参数错误",
        "991": "处理参数错误, 请填写 %s",
        "100": "数据添加失败，请检查服务端日志",
        "102": "数据更新失败，请检查服务端日志",
        "103": "数据删除失败，请检查服务端日志",
        "104": "数据停止失败，请检查服务端日志",
        "105": "数据恢复失败，请检查服务端日志",
        "106": "数据激活失败，请检查服务端日志",
        "109": "数据不存在，数据处理失败",
    }

    webProjectCampServiceImpl = None
    memeberWeightServiceImpl = None
    membersServiceImpl = None
    times_array = []

    def __init__(self, webProjectCampService, memeberWeightService, membersService):
        WebProjectCampRoute.webProjectCampServiceImpl = webProjectCampService
        WebProjectCampRoute.memeberWeightServiceImpl = memeberWeightService
        WebProjectCampRoute.membersServiceImpl = membersService
        return

    @staticmethod
    @WebProCampAdm.get('/fetch')
    def fetch():
        params = {"key": str(request.params.key).replace(" ", ""),
                  "pageSize": request.params.pageSize,
                  "pageNum": request.params.pageNum}
        res = WebProjectCampRoute.webProjectCampServiceImpl.fetch_projects(param=params)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': WebProjectCampRoute.ERROR_CODE["99"]}
        view_list = res['data']
        _pages = MyPager.make_pager(id="table_projects_msg", res=view_list, page_size=int(params['pageSize']),
                                    data_total=res['total'], single_pager=False)
        return {'code': 200, 'data': _pages, 'message': ""}

    @staticmethod
    @WebProCampAdm.get('/fetchOne')
    def fetch_one():
        id = request.params.id
        res = WebProjectCampRoute.webProjectCampServiceImpl.fetch_one(id=id)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': WebProjectCampRoute.ERROR_CODE["99"]}
        view_data = res['data']
        memList = []
        if len(view_data["mems_json"])>0:
            memList = json.loads(view_data["mems_json"])
        # view_data["mems_key_json"] = [mem["key"] for mem in memList]
        view_data["mems_key_json"] = memList
        return {'code': 200, 'data': view_data, 'message': ""}

    @staticmethod
    @WebProCampAdm.post('/add')
    def add():
        from datetime import datetime
        if request.json is not None:
            # 获取当前时间
            current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            data = request.json['data']
            data['create_time'] = current_time
            data['update_date'] = None
            res = WebProjectCampRoute.webProjectCampServiceImpl.add_project(project=data)
            if res['code'] == 200:
                return {'code': 200, 'data': res, 'message': ""}
            else:
                return {'code': res['code'], 'data': res, 'message': WebProjectCampRoute.ERROR_CODE["100"]}

    @staticmethod
    @WebProCampAdm.post('/update')
    def update():
        from datetime import datetime
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        if request.json is not None:
            data = request.json['data']
            projectId = request.json['id']
            data['update_date'] = current_time
            data['create_time'] = None
            res = WebProjectCampRoute.webProjectCampServiceImpl.update_project(project=data, id=projectId)
            # TODO 2024-03-16 2-1 会员编号作为会员餐食区分标记
            mems = json.loads(data['mems_json'])
            for memId in mems:
                # memId = mem["key"]
                mem = WebProjectCampRoute.memeberWeightServiceImpl.fetch_one(member_id=memId)["data"][0]
                project_sno = data['camp_sno'] + "%s" % str(mem["id"])
                WebProjectCampRoute.membersServiceImpl.update_member_sno(member_id=memId, peroject_sno=project_sno)
            if res['code'] == 200:
                return {'code': 200, 'data': res, 'message': ""}
            elif res['code'] == 404:
                return {'code': res['code'], 'data': res, 'message': WebProjectCampRoute.ERROR_CODE["109"]}
            else:
                return {'code': res['code'], 'data': res, 'message': WebProjectCampRoute.ERROR_CODE["102"]}

    @staticmethod
    @WebProCampAdm.get('/drop')
    def drop():
        id = request.params.id
        return WebProjectCampRoute.webProjectCampServiceImpl.drop_project(id=id)

    @staticmethod
    @WebProCampAdm.get('/fetchMemberTransJson')
    def fetchMemberTransJson():
        member_in_use = {"status": "MEM-001"}
        return WebProjectCampRoute.webProjectCampServiceImpl.fetchMemberTransJson(param=member_in_use)
